﻿using System.Configuration;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Configuration = NHibernate.Cfg.Configuration;

namespace Repository.NHibernate
{
    public static class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    string connStr = ConfigurationManager.ConnectionStrings["PostgreSQLConnectionString"].ConnectionString;
                    _sessionFactory = FluentNHibernate.Cfg.Fluently.Configure()
                        .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connStr))
                        .Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.Load("Repository.NHibernate")))
//                        .ExposeConfiguration(BuildSchema)
                        .BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(true, true);
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}